<template>
    <div id="main" style="height:100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { nextTick, onMounted } from 'vue';

const props = defineProps(['data'])
const handleData = ({ studentList, curStudent, tagList }) => {
    console.log(studentList, curStudent, tagList)
    // 筛选出同班同学
    const classmates = studentList.filter(stu => stu.class._id === curStudent.class._id)

    console.log(classmates)

    // 计算班级各科平均评分
    const classAvgRate = []
    tagList.forEach(({ title }) => {
        const filteredClassmates = classmates.filter(({ score }) => score[title])
        const sum = filteredClassmates.reduce((acc, { score }) => acc + score[title], 0)
        classAvgRate.push(parseFloat((sum / (filteredClassmates.length || 1)).toFixed(2)))
    })

    // 计算当前学生各科平均评分
    const curStuRate = []
    tagList.forEach(({ title }) => {
        curStuRate.push(curStudent.score[title] ? curStudent.score[title] : 0)
    })

    const legendData = [`${curStudent.class.title}班平均`, curStudent.studentname]
    return {
        'legendData': legendData,
        'radarIndicator': tagList.map(tag => ({
            'name': tag.title,
            'max': 5
        })),
        'seriesData': [
            {
                'name': legendData[0],
                'value': classAvgRate
            },
            {
                'name': legendData[1],
                'value': curStuRate
            }
        ]
    }
}

onMounted(() => nextTick(() => initChart()))

const initChart = () => {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));
    const { legendData, radarIndicator, seriesData } = handleData(props.data)
    console.log(legendData, radarIndicator, seriesData)
    // 绘制图表
    myChart.setOption({
        title: {
            text: ''
        },
        legend: {
            data: legendData
        },
        radar: {
            // shape: 'circle',
            indicator: radarIndicator
        },
        series: [
            {
                name: 'Budget vs spending',
                type: 'radar',
                data: seriesData
            }
        ]
    });
}
</script>